// pages/my/login/login.js
import { API_HOST } from "../../../utils/const"
import http from "../../../utils/http"
import util from '../../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: API_HOST,
    phonenum: '', //手机号
    second: 60,
    phonenum_err: '',
    phonecode_err: '',
    code: '', //验证码
    imgCode: "",//图形验证码
    imgCodeUrl: '',
    btnStatus: false, //验证码状态
    btnTxt: '发送验证码',
    reflesh: true,
    loginbtn: true,
    shareuserid: '',
    isDisabled: true,
    loginText: '登录',
    isGetCode: false,
    isShowModal: false,
    isCustom: '',
    loginBtnBgstatus: false, //登录按钮背景状态
    redirect: '', //登录之后跳转的页面
    isGetUser: false,
    userInfo: {},
    test: '',
    uuidCodeNum: util.guid(),
    userId: '',
    isRealUser: false,
    smsFlag: '',
    url:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('####login options:', options);
    let url = options.url || '/pages/index/index';
    this.setData({
      //redirect: options.redirect,
      url: options.url
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    //加载验证码
    // this.getNewCode();
  },
  goLogin: function (e) {
    let that = this;
    let isCustom = this.data.isCustom;
    //提交判断手机号
    if (!/^1[34578]\d{9}$/.test(that.data.phonenum)) {
      that.setData({ phonenum_err: '手机号码格式错误' })
      return false
    }
    if (!/^\d{6}$/.test(that.data.code)) {
      that.setData({ phonenum_err: '验证码错误请输入数字' })
      return false
    }
    //发送登录
    http({
      url: "/auth/loginVerify/",
      method: "POST",
      data: {
        username: that.data.phonenum,
        smsFlag: that.data.smsFlag,
        verifyCode: that.data.code
      },
      success: function (res) {
        console.log('====loginVerify:', res.isSuccess)
        if (res.code == 200 && res.isSuccess) {
          that.setData({
            //userId: res.data.userId,
            token: res.data.token,
            isDisabled: false,
            isRealUser: res.data.real_certification
          })
          console.log('####!isRealUser:', res.data.real_certification,'fan:');
          if (res.code == 200 && that.data.url.indexOf('/propertyDetailA/propertyDetailA') > -1 && wx.getStorageSync('clickIsPre') && !that.data.isRealUser) {
            wx.setStorageSync("token", that.data.token);
            wx.setStorageSync("isLoginStatus", true);
            wx.setStorageSync("phoneNum", that.data.phonenum);
            wx.setStorageSync("isRealUser", that.data.isRealUser);
            console.log('###########====', wx.getStorageSync('userId') );
            http({
              url: "/look/insertInfo/v1.0.0",
              method: "POST",
              data: {
                cityCode: wx.getStorageSync('cityCode') || '310100',
                preprocessId: that.data.cid
              },
              success: function (res) {
                console.log('====getUserId res:', res.code, 'typeof:', res.code == '-55');
                if (res.code === '-55') {
                  wx.setStorageSync("userId", res.data);
                  console.log('====login getStorageSync:', wx.getStorageSync('userId'), wx.getStorageSync('preId'));
                  wx.redirectTo({
                    url: '/pages/my/idCardAuth/idCardAuth?userId=' + res.data + '&phoneNum=' + wx.getStorageSync('phoneNum') + '&url=' + '/pages/index/success/success?preId=' + wx.getStorageSync('preId')
                  })
                } else {
                  return false;
                }
              }
            })
          } else if (res.code == 200 && res.data.token) {
            wx.setStorageSync("token", that.data.token);
            wx.setStorageSync("isLoginStatus", true);
            wx.setStorageSync("phoneNum", that.data.phonenum);
            wx.setStorageSync("isRealUser", that.data.isRealUser);
            wx.showToast({
              title: '登录完成',
              icon: "success",
              success: function () {
                wx.navigateBack();
                // wx.switchTab({
                //   url: that.data.url
                // })
              }
            })
          }
        } else if (res.code == 403) {
          wx.showModal({
            title: '请重新登录',
            showCancel: false,
            content: res.msg,
            success: function (res) {
              if (res.confirm) {
                //that.refreshImg();
                wx.clearStorageSync("token")
                wx.clearStorageSync("isLoginStatus");
                wx.clearStorageSync("phoneNum");
                wx.clearStorageSync("isRealUser");
                that.setData({
                  code: '',
                  phonecode_err: '',
                  isDisabled: true
                })
              }
            }
          })
        }else {
          wx.showModal({
            title: '注意',
            showCancel: false,
            content: res.msg,
            success: function (res) {
              if (res.confirm) {
                //that.refreshImg();
                wx.clearStorageSync("token")
                wx.clearStorageSync("isLoginStatus");
                wx.clearStorageSync("phoneNum");
                wx.clearStorageSync("isRealUser");
                that.setData({
                  code: '',
                  phonecode_err: '',
                  isDisabled: false
                })
              }
            }
          })
        }
      }
    })
  },
  //获取输入的手机号
  getPhoneNumber: function (e) {
    var that = this
    var phone = e.detail.value
    var isCustom = ''
    var loginText = '登录'
    if (/^1[34578]\d{9}$/.test(phone)) {
      that.setData({
        phonenum: phone
      })
    } else {
      that.setData({
        loginBtnBgstatus: false
      })
    }
  },
  //验证码
  getCodeNumber: function (e) {
    this.setData({
      code: e.detail.value,
      phonecode_err: ''
    })
  },
  //图片验证码
  getImgCode: function (e) {
    this.setData({
      imgCode: e.detail.value
    })
  },
  //发送短信验证码
  sendCode: function () {
    let that = this;
    //console.log('=====:', that.data.phonenum, 'reg:', !/^1[34578]\d{9}$/.test(that.data.phonenum));
    if (!/^1[34578]\d{9}$/.test(that.data.phonenum)) {
      that.setData({ phonenum_err: '手机号码格式错误' })
    } else {
      that.setData({ phonenum_err: '' })
      if (that.data.btnStatus) {
        return
      }
      /****
       * 
       *    else if (!/^[0-9|a-z|A-Z]{4}$/.test(that.data.imgCode)){
        that.setData({ phonenum_err: '图形验证码错误' })
      }
       * 
       */
      http({
        url: "/auth/sendSmsInfo",
        method: "POST",
        data: {
          uniqueCode: that.data.uuidCodeNum,
          verifyCode: that.data.imgCode,
          username: that.data.phonenum
        },
        success: function (res) {
          if (res.code == 200) {
            that.setData({
              btnStatus: true,
              smsFlag: res.data.smsFlag,
              isDisabled: false
            })
            countdown(that);
            wx.showToast({
              title: '已发送验证码',
              icon: "success"
            })
          } else if (res.code == 403) {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: res.msg,
              success: function (res) {
                if (res.confirm) {
                  //that.refreshImg();
                  wx.clearStorageSync("token")
                  wx.clearStorageSync("isLoginStatus");
                  wx.clearStorageSync("phoneNum");
                  wx.clearStorageSync("isRealUser");
                }
              }
            })
            that.setData({
              isDisabled: true
            })
          }else {
            wx.showModal({
              title: '注意',
              showCancel: false,
              content: res.msg,
              success: function (res) {
                if (res.confirm) {
                  //that.refreshImg();
                }
              }
            })
            that.setData({
              isDisabled: true
            })
          }
        }
      })
    }
  },
  refreshImg: function () {
    //this.getNewCode();
  },
  getNewCode: function () {
    var that = this;
    http({
      url: "/auth/verifyCode",
      data: {
        uniqueCode: that.data.uuidCodeNum
      },
      success: function (res) {
        if (res.code == 200) {
          var url = "data:image/png;base64," + res.data.verifyCodeImage;
          that.setData({
            imgCodeUrl: url
          })
        } else {
          return false
        }
      }
    })

  },
  goProtocol() {
    wx.navigateTo({
      url: '/pages/my/protocol/protocol'
    })
  }
})
//短信验证码60s倒计时
function countdown(that) {
  var second = that.data.second;
  if (second == 0) {
    that.setData({
      second: 60,
      btnStatus: false
    })
    return
  }
  var time = setTimeout(function () {
    that.setData({
      second: second - 1
    })
    countdown(that)
  }, 1000)
}